package com.online.onlineshop.controllers;

import com.online.onlineshop.services.exce.InsertingException;
import com.online.onlineshop.services.exce.ServiceException;
import com.online.onlineshop.services.exce.UserNameOccupiedExceoption;
import com.online.onlineshop.utils.ResultForFrontEnd;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpSession;
import java.util.Optional;

/*
 * controlle 的基本类
 * */
public class RootController {
    /*操作成功状态码*/
    public static final int ok = 200;
    //统一处理所定义的异常类
    protected final int getUidFromSession(HttpSession httpSession) {
        Object uid = httpSession.getAttribute("uid");
        return Optional.ofNullable(uid).map(uuid -> Integer.parseInt(uuid.toString())).orElse(0);
    }
    protected final String getUserNameFromSession(HttpSession httpSession) {
        return httpSession.getAttribute("username").toString();
    }


    @ExceptionHandler(ServiceException.class)
    public ResultForFrontEnd<Void> DealWithException(Throwable e) {
        ResultForFrontEnd<Void> forFrontEnd = new ResultForFrontEnd<>(e);

        if (e instanceof UserNameOccupiedExceoption) {
            forFrontEnd.setStateCode(4000);
            forFrontEnd.setMsg(e.getMessage());
        } else if (e instanceof InsertingException) {
            forFrontEnd.setStateCode(5000);
            forFrontEnd.setMsg(e.getMessage());
        }
        return forFrontEnd;
    }


}
